package com.baizhiedu.rsm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baizhiedu.rsm.entity.StudentMessage;
import com.baizhiedu.rsm.entity.Subject;
import com.baizhiedu.rsm.service.SubjectService;
import com.baizhiedu.rsm.util.ParseExcelForSubject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author lby
 */
@Controller
@RequestMapping("subject")
public class SubjectController {
    @Autowired
    private SubjectService subjectService;

    /**
     *  修改信息 行内编辑
     * @param subject
     * @return
     */
    @RequestMapping("updateOne")
    @ResponseBody
    public Map updateOne(Subject subject){
        return subjectService.updateOne(subject);
    }

    /**
     * 删除习题信息
     * @param datalist
     * @return
     */
    @RequestMapping("deleteSelete")
    @ResponseBody
    public String deleteSelete(String datalist){
        List<Subject> subjects = JSON.parseObject(datalist,new TypeReference<List<Subject>>(){});
        subjectService.deleteSelect(subjects);
        return "";
    }

    @RequestMapping("addSubject")
    public String addSubject(String id,String subContent){
        Subject subject = new Subject();
        subject.setContent(subContent);
        subject.setSid(Integer.parseInt(id));
        subjectService.addSubject(subject);
        return "redirect:/addSubject.html";
    }

    @RequestMapping("showAllSubject")
    @ResponseBody
    public List<Subject> showAllSubject(){
        return subjectService.showAllSubject();
    }

    @RequestMapping("showSubject")
    @ResponseBody
    public List<Subject> showSubject(HttpSession session){
        List<Subject> subjects = (List<Subject>)session.getAttribute("subjects");
        return subjects;
    }

    /**
     * 导入题目
     *
     * @param request
     *            HttpServletRequest 用来存储和获取数据。
     * @param response
     *            HttpServletResponse 用来响应数据信息。
     * @return 重定向到展示用户列表。
     */
    @RequestMapping("/importSubject")
    public String importUser(HttpServletRequest request, MultipartFile fileName, HttpServletResponse response) throws IOException {
        try {

            // 1. 从流中获取文件数据
            InputStream inputStream = fileName.getInputStream();
            // 读取文件数据
            ParseExcelForSubject.parseAndImportUser(inputStream, subjectService);
            // 通过工具类保存用户。
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/addSubject.html";
    }
}
